//
//  singlePeripheral.m
//  Lazy
//
//  Created by yoky on 14-6-27.
//  Copyright (c) 2014年 Echo. All rights reserved.
//

#import "singlePeripheral.h"
#import "WsHUD.h"
#import "RecInfo.h"

@interface singlePeripheral (){
    BOOL isConnect;
    NSMutableArray *peripherals;
}
@property (strong, nonatomic) CBCharacteristic      *discoveredCBCharacteristic;
@property (strong, nonatomic) CBCharacteristic      *readCBCharacteristic;
@end

@implementation singlePeripheral
@synthesize readData, isSyning, isFindDeviceing;
@synthesize centeralManager;
@synthesize discoveredPeripheral;
@synthesize todayDic;

static singlePeripheral *_instance = nil;
+ (singlePeripheral *)instance {
    @synchronized (self) {
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }
    return _instance;
}
-(id)init {
    self = [super init];
    peripherals = [[NSMutableArray alloc] init];
    readData = [[NSMutableData alloc] init];
    curArray = [[NSMutableArray alloc] init];
    todayDic = [[NSMutableDictionary alloc] init];
    isConnect = NO;
    centeralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
    [NC addObserver:self selector:@selector(endSyn) name:NOTI_END_SYN_DATA object:nil];
    return self;
}
- (void)startScan
{
    if (!isConnect) {
        
        NSLog(@"startScan");
        
        isFindDeviceing = YES;
        
//        if ([UD boolForKey:NOTI_DEVICE_FINISH]) {
            [WsHUD showHUDWithLabel:STR(@"正在搜寻设备...") modal:YES timeoutDuration:0];
//        }
//        [WsHUD showHUDWithLabel:STR(@"正在搜寻设备...") modal:YES timeoutDuration:0];
        
        //check if serviceUUIDS contain NSString
        NSString *serviceID =  @"FFF0";
        NSMutableArray *services = [[NSMutableArray alloc]init];
        CBUUID *serUUID = [CBUUID UUIDWithString:serviceID];
        [services addObject:serUUID];
        
        [[singlePeripheral instance].centeralManager retrieveConnectedPeripherals];
        [[singlePeripheral instance].centeralManager scanForPeripheralsWithServices:services options:nil];
        //        [[singlePeripheral instance].centeralManager scanForPeripheralsWithServices:nil options:nil];
        //
        isConnect = YES;
    }
}

- (BOOL)supportLEHardware
{
    NSString * state = nil;
    BOOL is_support = YES;
    switch ([[singlePeripheral instance].centeralManager state])
    {
        case CBCentralManagerStateUnsupported:
            is_support = NO;
            state = @"The platform/hardware doesn't support Bluetooth Low Energy.";
            break;
        case CBCentralManagerStateUnauthorized:
            state = @"The app is not authorized to use Bluetooth Low Energy.";
            break;
        case CBCentralManagerStatePoweredOff:
            state = @"Bluetooth is currently powered off.";
            break;
        case CBCentralManagerStatePoweredOn:
            return TRUE;
        case CBCentralManagerStateUnknown:
        default:
            return false;
    }
    NSLog(@"Central manager state: %@", state);
    if (is_support == NO) {
//        UIAlertView *alvert = [[UIAlertView alloc] initWithTitle:STR(@"提示") message:STR(@"此手机不支持蓝牙4.0") delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        [alvert show];
    }
    return false;
}
/** Once the disconnection happens, we need to clean up our local copy of the peripheral
 */
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"Peripheral Disconnected");
    [singlePeripheral instance].discoveredPeripheral = nil;
    isConnect = NO;
    // We're disconnected, so start scanning again
    [self startScan];
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    if (![self supportLEHardware])
    {
        //        @throw ([NSError errorWithDomain:@"Bluetooth LE not supported"
        //                                    code:999
        //                                userInfo:nil]);
    }
    if (central.state != CBCentralManagerStatePoweredOn) {
        // In a real app, you'd deal with all the states correctly
        return;
    }
    // The state must be CBCentralManagerStatePoweredOn...
    // ... so start scanning
    [self startScan];
    
    return;
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
//    NSLog(@"Discovered %@ at %@", peripheral.name, RSSI);
    NSLog(@"Discovered %@ at %@", peripheral, RSSI);
    [NC postNotificationName:NOTI_DEVICE_NAME object:peripheral];
    NSLog(@"advertisementData %@", advertisementData);
    
    [WsHUD findAndHideHUD:NO];
    
//    if ([singlePeripheral instance].discoveredPeripheral != peripheral) {
//        [[singlePeripheral instance].centeralManager stopScan];
//        [singlePeripheral instance].discoveredPeripheral = peripheral;
//        // And connect
//        NSLog(@"Connecting to peripheral %@", peripheral);
//        [[singlePeripheral instance].centeralManager connectPeripheral:peripheral options:nil];
//    }
}
-(void)connectDevice:(CBPeripheral*)peripheral{
    if ([singlePeripheral instance].discoveredPeripheral != peripheral) {
        [[singlePeripheral instance].centeralManager stopScan];
        [singlePeripheral instance].discoveredPeripheral = peripheral;
        // And connect
        NSLog(@"Connecting to peripheral %@", peripheral);
        
        [WsHUD showHUDWithLabel:STR(@"正在连接设备...") modal:YES timeoutDuration:0];
        
        
        [[singlePeripheral instance].centeralManager connectPeripheral:peripheral options:nil];
    }
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"Peripheral Connected");
    peripheral.delegate = self;//因为在后面我们要从外设蓝牙那边再获取一些信息，并与之通讯，这些过程会有一些事件可能要处理，所以要给这个外设设置代理，比如：
    // Search only for services that match our UUID
    [peripheral discoverServices:nil];//查询所有蓝牙服务
}
//返回的蓝牙服务通知通过代理实现
- (void)peripheral:(CBPeripheral *)aPeripheral didDiscoverServices:(NSError *)error {
    NSLog(@"didDiscoverServices:\n");
    if (error) {
        NSLog(@"Discovered services for %@ with error: %@", aPeripheral.name, [error localizedDescription]);
        return;
    }
    if (!error) {
        NSLog(@"====%@\n", aPeripheral.name);
        for (CBService *service in aPeripheral.services){
//            NSLog(@"Service found with UUID: %@(%@)\n", service.UUID.data,service.UUID);
            //            NSLog(@"discoverCharacteristics for service: %@", service.UUID.UUIDString);／／ios5崩溃
            [aPeripheral discoverCharacteristics:nil forService:service];
        }
    }
    else {
        NSLog(@"Service discovery was unsuccessfull !\n");
    }
}
//在这个方法中我们要找到我们所需的服务的特性 然后调用setNotifyValue方法告知我们要监测这个服务特性的状态变化
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    isConnect = YES;
    if (error){
//        NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
        return;
    }
    // Again, we loop through the array, just in case.
    for (CBCharacteristic *characteristic in service.characteristics) {
//        NSLog(@"characteristic : %@", characteristic.UUID);
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF1"]]) {//往FFF1发送数据
            self.discoveredCBCharacteristic = characteristic;
            [WsHUD findAndHideHUD:NO];
            
            [NC postNotificationName:NOTI_DEVICE_CONNECTED object:peripheral];
            
            isFindDeviceing = NO;
            [self performSelectorOnMainThread:@selector(synCurTimeToDeviceMainThread) withObject:nil waitUntilDone:YES];
        }
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF2"]]) {
            self.readCBCharacteristic = characteristic;
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
        //        [peripheral setNotifyValue:YES forCharacteristic:characteristic];
    }
}
-(void)synCurTimeToDeviceMainThread{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(synCurTimeToDevice) object:nil];
    [self performSelector:@selector(synCurTimeToDevice) withObject:nil afterDelay:3];
}
- (NSString *)ToHex:(uint16_t)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    uint16_t ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:
                nLetterValue = [NSString stringWithFormat:@"%u",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
        
    }
    if ([str length] == 1) {
        str = [NSString stringWithFormat:@"0%@", str];
    }
    return str;
}
-(void)synCurTimeToDevice{
    
    NSDateFormatter *formatter	=  [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yy"];//HH:mm
    NSString  *strYear = [formatter stringFromDate:[NSDate date]];
    [formatter setDateFormat:@"MM"];
    NSString  *strMonth = [formatter stringFromDate:[NSDate date]];
    [formatter setDateFormat:@"dd"];
    NSString  *strDay = [formatter stringFromDate:[NSDate date]];
    [formatter setDateFormat:@"HH"];
    NSString  *strHour = [formatter stringFromDate:[NSDate date]];
    [formatter setDateFormat:@"mm"];
    NSString  *strMin = [formatter stringFromDate:[NSDate date]];
    [formatter setDateFormat:@"ss"];
    NSString  *strSecs = [formatter stringFromDate:[NSDate date]];
    
    NSString *time = [NSString stringWithFormat:@"%@%@%@%@%@%@", [self ToHex:[strYear integerValue]], [self ToHex:[strMonth integerValue]], [self ToHex:[strDay integerValue]], [self ToHex:[strHour integerValue]], [self ToHex:[strMin integerValue]], [self ToHex:[strSecs integerValue]]];
    NSLog(@"同步时间");
    NSString *str = [NSString stringWithFormat:@"%@%@%@%@", @"324345", @"0930", time, @"5533"];
    [self sendDataToBluetooth:str];
}

//3.7给蓝牙发数据
//这时还会触发一个代理事件
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    
}
NSData * dataWithStringyy(NSString *sendString) {
    sendString = [sendString uppercaseString];
    if ([sendString length] % 2 == 0) {
        int bitCount = (int)[sendString length];
        NSMutableData *sendData = [NSMutableData data];
        for (int i = 0; i < bitCount; i+= 2) {
            NSString *subString = [sendString substringWithRange:NSMakeRange(i, 2)];
            //字母处理 判断是否有 字母
            BOOL withChar = NO;
            int bufferWithChar = 0;
            for (int r = 0; r < 2; r++) {
                NSString *tempString = [subString substringWithRange:NSMakeRange(r, 1)];
                NSData *data = [tempString dataUsingEncoding:NSASCIIStringEncoding];
                char tempBuffer = 0;
                [data getBytes:&tempBuffer];
                if (tempBuffer < 65) {
                    bufferWithChar += (r==0?16:1) * (tempBuffer - 48);
                }
                if (tempBuffer >= 65) {
                    withChar = YES;
                    bufferWithChar += (r==0?16:1) * (tempBuffer - 55);
                }
            }
            char buffer = 0;
            if (withChar) {
                buffer = bufferWithChar;
            } else {
                buffer = [subString intValue];
                int temp = 6 * (buffer / 10);
                buffer += temp;
            }
            [sendData appendBytes:&buffer length:1];
        }
        return sendData;
    }
    return nil;
}
//3处理蓝牙发过来的数据
//在这个方法中我们要找到我们所需的服务的特性 然后调用setNotifyValue方法告知我们要监测这个服务特性的状态变化
- (void) peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    //    NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
    //    NSLog(@"characteristic.UUID (%@) Received:  %@", [characteristic.UUID UUIDString], stringFromData);
    char *pRecv1 = (char*)[characteristic.value bytes];
    if (pRecv1) {
        //        NSString *string = [NSString stringWithUTF8String:pRecv1];
        //        if ([string length] > 0) {
        //            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:string delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        //            [alert show];
        //        }
    }
    //324345 645533
    if (pRecv1) {
        for (int i=0; i<[characteristic.value length]; i++) {
            //            NSLog(@"recvxxx:[%d]:0x%02x %c", i, pRecv1[i], pRecv1[i]);
            
//            NSLog(@"read characteristic (%@) :  0x%02x", [characteristic.UUID UUIDString], pRecv1[i]);
            
            if (bBeginAddData1 && bBeginAddData2 && bBeginAddData3) {
                [readData appendBytes:pRecv1+i length:1];
            }
            if (pRecv1[i] == 0x32) {
                bBeginAddData1 = YES;
            }else if (pRecv1[i] == 0x43) {
                bBeginAddData2 = YES;
            }else if (pRecv1[i] == 0x45) {
                NSLog(@"begin");
                bBeginAddData3 = YES;
            }
            

            if (pRecv1[i] == 0x55) {
                bEndAddData2 = YES;
                
            }else if (pRecv1[i] == 0x33){
                bEndAddData3 = YES;
            }
            
            if (bEndAddData2 && bEndAddData3) {
                bBeginAddData1 = NO; bBeginAddData2 = NO; bBeginAddData3 = NO;
                isSyning = NO;
                NSLog(@"end");
                [NC postNotificationName:NOTI_END_SYN_DATA object:nil];
            }
        }
    }
}
-(void)writeDataToFile{
    
}

-(void)endSyn{
    
    [curArray removeAllObjects];
    
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    NSString *path1 = [RecInfo storePathWithFileName:ICUPRECINFO];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path1]) {
        NSArray *array =  [RecInfo unarchiverObjectFromPath:path1 key:ICUPRECINFO];
        [tempArray addObjectsFromArray:array];
    }
    NSDateFormatter *formatter	=  [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyMMdd"];
    NSString  *curdate = [formatter stringFromDate:[NSDate date]];
    //查看老数据是否有保存今天以前的数据，如果有则add保存的数据
    for (NSMutableArray *subArray in tempArray) {
        if (subArray.count > 4) {
//            NSNumber *ml = [subArray objectAtIndex:0];
            NSNumber *year = [subArray objectAtIndex:1];
            NSNumber *month = [subArray objectAtIndex:2];
            NSNumber *day = [subArray objectAtIndex:3];
//            NSNumber *secs = [subArray objectAtIndex:4];
            NSString *todayTime = [NSString stringWithFormat:@"%02d%02d%02d", [year integerValue], [month integerValue], [day integerValue]];
            if ([curdate integerValue] > [todayTime integerValue]) {
                [curArray addObject:subArray];
            }
        }
    }
    
    NSData *encrydata = [singlePeripheral instance].readData;
    
    char *pRecv = (char*)[encrydata bytes];
    
    NSInteger remainder = encrydata.length%5;
    NSInteger num = encrydata.length/5;
    NSInteger totalLenght = encrydata.length;
    
    int count = 0;
    for (int i=0; i<totalLenght-remainder; i=i+5) {
        NSMutableArray *subArray = [[NSMutableArray alloc] init];
        for (int j=0; j<5; j++) {
            [subArray addObject:[NSNumber numberWithChar:pRecv[i+j]]];
//            printf("test 0x%02x ", pRecv[i+j]);
        }
        if (tempArray.count > 0) {
            if (subArray.count > 4) {//肯定大于4
                NSNumber *year = [subArray objectAtIndex:1];
                NSNumber *month = [subArray objectAtIndex:2];
                NSNumber *day = [subArray objectAtIndex:3];
                NSString *todayTime = [NSString stringWithFormat:@"%02d%02d%02d", [year integerValue], [month integerValue], [day integerValue]];
                if ([curdate integerValue] <= [todayTime integerValue]) {
                    [curArray addObject:subArray];
                }else{
                    [curArray addObject:subArray];
                }
            }
        }else{
            [curArray addObject:subArray];
        }
        count++;
        if (count == num) {
            NSLog(@"总共%d个数据", count);
//            [NC postNotificationName:ICUP_LAST_WATER_NUM object:subArray];
        }
    }
    NSString *path = [RecInfo storePathWithFileName:ICUPRECINFO];
    [RecInfo archiverObject:curArray path:path key:ICUPRECINFO];
    
    [NC postNotificationName:ICUP_LAST_WATER_NUM object:nil];
}

-(void)sendDataToBluetooth:(NSString*)str{
//    str = @"324345bb5533";
    if (!self.discoveredCBCharacteristic) {
        NSLog(@"cannot send data");
        return;
    }
    NSLog(@"send : %@", str);
    bEndAddData1 = NO; bEndAddData2 = NO; bEndAddData3 = NO;
    [readData resetBytesInRange:NSMakeRange(0, [readData length])];
    [readData setLength:0];
    if ([str isEqualToString:@"324345bb5533"]) {
        isSyning = YES;
    }
    
    for (int i=0; i<[str length]; i=i+2) {
        NSRange range;
        range.location = i;
        range.length = 2;
        NSString *subStr = [str substringWithRange:range];
//        NSLog(@"(write to %@): %@", [[self.discoveredCBCharacteristic UUID] UUIDString], subStr);
        [discoveredPeripheral writeValue:dataWithStringyy(subStr) forCharacteristic:self.discoveredCBCharacteristic type:CBCharacteristicWriteWithResponse];
    }
}

- (float)getTodayWaterMeasure{
    NSMutableArray *tempArray = nil;
    if (curArray.count > 0) {
        tempArray = curArray;
    }else{
        tempArray = [[NSMutableArray alloc] init];
        NSString *path = [RecInfo storePathWithFileName:ICUPRECINFO];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            NSArray *array =  [RecInfo unarchiverObjectFromPath:path key:ICUPRECINFO];
            [tempArray addObjectsFromArray:array];
        }
    }
    float totalNum = 0;
    NSDateFormatter *formatter	=  [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyMMdd"];
    NSString  *strdate = [formatter stringFromDate:[NSDate date]];
    for (NSMutableArray *array in tempArray) {
        if (array.count > 4) {
            NSNumber *ml = [array objectAtIndex:0];
            NSNumber *year = [array objectAtIndex:1];
            NSNumber *month = [array objectAtIndex:2];
            NSNumber *day = [array objectAtIndex:3];
            NSNumber *secs = [array objectAtIndex:4];
            NSString *todayTime = [NSString stringWithFormat:@"%02d%02d%02d", [year integerValue], [month integerValue], [day integerValue]];
            if ([strdate isEqualToString:todayTime]) {
                totalNum = totalNum+[ml floatValue];
                
                [todayDic setObject:ml forKey:secs];
            }
        }
    }
    //for test
//    [todayDic setObject:@"20" forKey:@"13"];
//    [todayDic setObject:@"30" forKey:@"14"];
//    [todayDic setObject:@"1000" forKey:@"15"];
//    [todayDic setObject:@"46" forKey:@"16"];
    //for test
    
    return totalNum;
}
+ (int)getSroce:(int)ml{
    int score = 0;
    NSNumber *number = [UD objectForKey:EVERYDAY_WAITER_NUM];
    if (!number) {
        number = [NSNumber numberWithInt:1371];
    }
    if (ml  > 0) {
        score = ml *100/[number intValue];
        if (score == 0) {
            score = 1;
        }
    }else{
        score = 0;
    }
    return score;
}

+(NSInteger)calculateAgeFromBirthday:(NSString *)abirthday {
    NSInteger age=0;
    if (abirthday) {
        NSArray *sub = [abirthday componentsSeparatedByString:@"-"];
        if (sub.count==3) {
            NSInteger year = [[sub objectAtIndex:0] integerValue];
            NSDateFormatter *fm=[[NSDateFormatter alloc] init];
            [fm setDateFormat:@"yyyy"];
            NSInteger currentYear=[[fm stringFromDate:[NSDate date]] integerValue];
            age=currentYear-year;
        }
    }
    return age;
}
+(NSInteger)getWaiterNum{
    return [[UD objectForKey:EVERYDAY_WAITER_NUM] integerValue];
}
+(int)calWaiterNum{
    int W = [[UD objectForKey:ICUP_CHANGE_WEIGHT] integerValue];
    int H = [[UD objectForKey:ICUP_CHANGE_GAO] integerValue];
    NSInteger x = [singlePeripheral calculateAgeFromBirthday:[UD objectForKey:ICUP_CHANGE_BIR]];
    int P = 2;//室内
    if ([[UD objectForKey:ICUP_CHANGE_ADDR] isEqualToString:@"户外"]) {
        P = 1;//户外
    }
    int b = 0;//体质不易出汗
    if ([[UD objectForKey:ICUP_CHANGE_TIZHI] isEqualToString:@"易出汗"]) {
        b = 1;//易出汗
    }
    int Y = 0;
    if ([[UD objectForKey:ICUP_CHANGE_SEX] isEqualToString:@"男"]) {
        Y=(120*(x-15)+1800+(H-170)*2+(W-(H-80)*0.7))*P+b*300;
        //(P=1或P=2) (b=1或b=0) (26≥x≥15);
        
    }else{
        Y=(120*(x-15)+1600+(H-160)*1.5+(W-(H-70)*0.6))*0.8*P+b*210;
        // (P=1或P=2) (b=1或b=0)  (26≥x≥15)
    }
    [UD setObject:[NSNumber numberWithInt:Y] forKey:EVERYDAY_WAITER_NUM];
    
    return Y;
    /*
     男性饮水量计算：
     
     Y={120×(x-15)+1800+(H-170)×2+[W-(H-80)×0.7]}×P+b×300
     (P=1或P=2) (b=1或b=0) (26≥x≥15)
     
     Y={2400-37×(x-26)+(H-170)×2+[W-(H-80)×0.7]}×P+b×200
     (P=1或P=2) (b=1或b=0) (x>26)
     
     女性饮水量计算：
     Y={120×(x-15)+1600+(H-160)×1.5+[W-(H-70)×0.6]}×0.8P+b×210
     (P=1或P=2) (b=1或b=0)  (26≥x≥15)
     
     Y={2100-37×(x-26)+(H-160)×1.5+[W-(H-70)×0.6]}×0.8P+b×180
     (P=1或P=2) (b=1或b=0)  (x>26)
     
     W为体重
     H为身高
     x为年龄
     P=1为户外 P=2为室内
     b=1为体质易出汗，b=0为体质不易出汗
     */
}
@end






